package com.wooming.myserver.service.impl;

import com.wooming.myserver.dto.RankDTO;
import com.wooming.myserver.mapper.RankMapper;
import com.wooming.myserver.service.inter.RankService;
import com.wooming.myserver.util.PageResult;
import com.wooming.myserver.vo.RankVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 排行榜服务实现
 *
 * @author Wooming
 */
@Service
public class RankServiceImpl implements RankService {
    private final RankMapper rankMapper;

    @Autowired
    public RankServiceImpl(RankMapper rankMapper) {
        this.rankMapper = rankMapper;
    }

    @Override
    public PageResult<RankVO> getRank(RankDTO rankDTO) {
        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        params.put("orderBy", "total." + rankDTO.getOrderBy());
        params.put("pageSize", rankDTO.getPageSize());
        Integer base = (rankDTO.getPageNum() - 1) * rankDTO.getPageSize();
        params.put("base", base);

        // 查询并构建数据
        AtomicReference<Integer> rank = new AtomicReference<>(1);
        List<RankVO> rankList = rankMapper.getRank(params)
                .stream()
                .map(rankVO -> setRank(rankVO, base, rank.getAndSet(rank.get() + 1)))
                .toList();

        // 获取总数并构建总页数
        Integer count = rankMapper.getCount();
        int totalPage = (count + rankDTO.getPageSize() - 1) / rankDTO.getPageSize();
        return new PageResult<>(
                rankDTO.getPageNum(),
                rankDTO.getPageSize(),
                totalPage, rankList
        );
    }

    private RankVO setRank(RankVO rankVO, Integer base, Integer rank) {
        rankVO.setRank(rank + base);
        return rankVO;
    }
}
